import { Clerk } from '@clerk/clerk-js'
import { zhCN } from '@clerk/localizations'
import { usePathname } from 'next/navigation'

export type SignType =
  | 'openSignIn'
  | 'openSignUp'
  | 'openOrganizationProfile'
  | 'openCreateOrganization'

const NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY =
  process?.env?.['NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY'] || ''

const loadClerk = async (locale?: any) => {
  const clerk = new Clerk(NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY)
  await clerk.load(locale ? { localization: locale } : {})
  return clerk
}

export const useSignContext = () => {
  const pathname = usePathname()

  const openSignIn = async () => {
    const clerk = await loadClerk(zhCN)
    clerk.openSignIn({ fallbackRedirectUrl: pathname })
  }

  const openSignUp = async () => {
    const clerk = await loadClerk(zhCN)
    clerk.openSignUp({ fallbackRedirectUrl: pathname })
  }

  const closeSignIn = async () => {
    const clerk = await loadClerk(zhCN)
    clerk.closeSignIn()
  }

  const closeSignUp = async () => {
    const clerk = await loadClerk(zhCN)
    clerk.closeSignUp()
  }

  const openOrganizationProfile = async () => {
    const clerk = await loadClerk(zhCN)
    clerk.openOrganizationProfile()
  }

  const openCreateOrganization = async () => {
    const clerk = await loadClerk(zhCN)
    clerk.openCreateOrganization()
  }

  return {
    openSignIn,
    closeSignIn,
    openSignUp,
    closeSignUp,
    openOrganizationProfile,
    openCreateOrganization
  }
}
